package com.xysd.express.activity.alipay;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.xysd.express.base.BaseActivity;

import java.util.Map;

/**
 * Created by donghui on 2017/10/9.
 */

public abstract class BaseAlipayActivity extends BaseActivity {

    protected String order_str;//订单号
    protected String money_str;//支付金额
    protected String timestamp;//时间戳
    protected String version;//sdk版本号
    protected String notify_url;//回调地址
    protected String subject;//提示信息
//    protected int payFrom;//支付来自哪儿，1充值，2订单支付，3需求支付

//    protected int order_id;//来自下单的支付需要跳转到订单详情的订单id


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PayTask payTask = new PayTask(mActivity);
        version = payTask.getVersion();

    }

    @SuppressLint("HandlerLeak")
    protected Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.i("payResult","code:"+resultStatus+"---info:"+resultInfo);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(BaseAlipayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(BaseAlipayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    /** 支付宝支付业务：入参app_id */
    public static final String APPID = "2016091901928343";

    /** 支付宝账户登录授权业务：入参pid值 */
    public static final String PID = "";
    /** 支付宝账户登录授权业务：入参target_id值 */
    public static final String TARGET_ID = "";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /** 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1 */
    public static final String RSA2_PRIVATE ="MIIEpQIBAAKCAQEAxW6SsvKnOzEKFdS90OWAbVqCW3D5ucjyvMnWVQ0skzlIfrDV6N2Lbr2tL8hbKq6zFGf9Ih6sdAGmf8yrd3wd/30GMwui5dmI3oFMPMgGjTnZRLSHHmRO3bStjF3StdevSCJjHUoIr590kdDQAgcaOj+ECzmRTgxYQ/3F3HIzIGSMRqLpPbLRRPVbhtFd72hbhcHpwIxDLBTE1ZRC7izPcUPLQSCxDLtUBeTNy5YbBRHKP/MvjoKrgfw1Q4+WDb7g+m7d40XSCze+/wUOKPmY4uu9TNCGA+Ove1S38KL8n6mIFOpJdFar/UI0LeT7PdwqoDyDIgVk0kKndBOq+cG8XwIDAQABAoIBAQCzZiE5J9Mbrxjp83Ezw4cqVscDDiptThJ7x6/RgvIRKUkdjdQiEEXlr8cSFy34H9yr2z4h5dtwYhuIH1NjdE3R3Spn8dfoof2Dqdu7k0qYw4sQqjXpQN6FCOt2E78m60Dj/BMyBxbTdsI2yZZpcUi8ywBSLtJBKGiAB7Xl9YNNl1dkIhG+OWJkvezUMkADA5hCdHgLWJIFJ8mK/L+cFHzU1mU1rYBAxUGiBlyHeo7gTRqBOtutMYxj42gASIzi9tNM5bTc6UZdmjDr4I4JztpEIBWXyRIy1l1bebJ6kPb/0ilFs1/upSfAApGktUfJeAHXVCMvHVJPlI7YOfrIgZOhAoGBAOMeS+YjWFh8061r/8sGD4gZhud0iKcA/pqgb6QVZ7E7qxHQWHwW7711y/mdi6Jk7JqwZzBUqBhSqi2lgYyuWXrze9cmBDxAImZphM56Je8qr+dKk0TtTg1c4bQikd3K6bBgFdRSxxWvu3ZZEuI5THxOclTmSIavMiNIBlMNDwSvAoGBAN6J2kt4+68ho/vlXvHLVqdeOvjxhncMjYKtuWIqRW4X3oC9FDyELduYwCVP/iP+tydSni5z6bVpCZhHZGh5PNVl9lDjIw7SwSEr9DKEsKlZnWY2uadvcGRBTLmu636dRa+8g3F5AwE/oqsTBnJjLNui6cd1wcm+ZACON4CJtQ9RAoGAHiLO/2KBPnyRudkyv8W2GeEJPX0BBOfk4K+ZILSWZbX9JQf4Nb71YLZYsm5tMMcjfgMaLheNlmyhmBz166zWwrG8JPguZ7A64EvwC1W54tpPLOmAUQ0L5koEyNotcLiT+YtGWj4BnKcMwM9g6hOgSn4+PXWw+e4VQQk1jZ+V9pECgYEAq4M3eV+fKtUUm7mmOVjsSkY30VHkvrAwCH14GY5WwIko9bPEevesmEjcHmXOi1NvOaFVRJwVjbmMqY6sdlCqcBYLhz/n7y7DpptHs//MYFkvFG4tHDypNLuXNKz51zXDVbRG4hfQFxBCgPNCzrpdAlJHN3EskB5q2HrDkA+SOmECgYEApA/PjnvgHFli1ZZRN5hqRA2I3v6WqZdXfE0kPxWtSyrLYMxU3aobVko/I5BTxklITgnl6bQBY+ssusK8wkgCp23kpANjEdtWWjmn7lga2IBbRmFWc+22IY4Kg0a+uNJqXlh4HlFIRi6nMmdG9Q4xQRHCkzgxmnRu2Uy6JVBx9ao=";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    /**
     * 支付宝支付业务
     *
     *
     */
    public void payV2() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2,order_str,money_str,timestamp
                ,version,notify_url,subject);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(BaseAlipayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @Override
    protected abstract void init();
}
